package com.das.mechanic_base.mvp.view.create;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.maintain.X3OrginFactoryPlanAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.even.OptionMainTainPlan;
import com.das.mechanic_base.bean.maintain.MainTainPlanBean;
import com.das.mechanic_base.bean.maintain.UpdateMainTainPlan;
import com.das.mechanic_base.mvp.contract.maintain.X3OrginFactoryPlanContract;
import com.das.mechanic_base.mvp.presenter.maintain.X3OrginFactoryPresenter;
import com.das.mechanic_base.utils.SoftKeyboardStateHelper;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.widget.X3CenterImageSpan;
import com.kproduce.roundcorners.RoundTextView;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = X3AppRouterConstants.Router.MAINTAIN_PLANE)
public class X3OriginalFactoryPlanActivity extends X3BaseActivity<X3OrginFactoryPresenter> implements X3OrginFactoryPlanContract.View {

    @BindView(R2.id.rlv_plan)
    RecyclerView rlv_plan;
    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.rv_cancel)
    RoundTextView rv_cancel;
    @BindView(R2.id.rv_affirm)
    RoundTextView rv_affirm;
    @BindView(R2.id.tv_title)
    TextView tv_title;
    @BindView(R2.id.tv_top_tip)
    TextView tv_top_tip;
    @BindView(R2.id.v_bottom)
    View v_bottom;

    private String title;
    X3OrginFactoryPlanAdapter mAdapter;
    private long carId;
    private ArrayList<MainTainPlanBean> mainTainPlanBeanList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_origin_factory_plan;
    }

    @Override
    protected void initView() {
        X3StatusBarUtil.darkMode(this);
        rl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this), 0, 0);
        tv_title.setText(getString(R.string.x3_orgin_factory_plan_title));
        tipsContent(this);
        initIntentParams();
        configRlv();
        getMainTainPlanListData(carId);
        keyBoardParams();
    }

    Handler keyBoardHandler = new Handler();
    //键盘高度参数
    private void keyBoardParams(){
        SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(this.getWindow().getDecorView());
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                int pxh = keyboardHeightInPx-X3StatusBarUtil.getStatusBarHeight(X3OriginalFactoryPlanActivity.this) + X3ScreenUtils.dip2px(5,X3OriginalFactoryPlanActivity.this);
                adjustBottomViewParams(pxh);
                adjustRv(pxh+ X3ScreenUtils.dip2px(60,X3OriginalFactoryPlanActivity.this));
            }

            @Override
            public void onSoftKeyboardClosed() {
                keyBoardHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adjustBottomViewParams(X3ScreenUtils.dip2px(8,X3OriginalFactoryPlanActivity.this));
                        adjustRv(X3ScreenUtils.dip2px(60,X3OriginalFactoryPlanActivity.this));
                    }
                }, 150);
            }
        });
    }

    private void adjustBottomViewParams(int pxH){
        if (v_bottom != null){
            try {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) v_bottom.getLayoutParams();
                layoutParams.height =  pxH;
                layoutParams.width = 1;
                v_bottom.setLayoutParams(layoutParams);

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void adjustRv(int pxH){
        rlv_plan.setPadding(X3ScreenUtils.dip2px(16,this),0,X3ScreenUtils.dip2px(16,this),pxH);
    }

    private void tipsContent(Context context) {
        //解决图片背景高亮
        tv_top_tip.setHighlightColor(Color.parseColor("#00000000"));

        String des = getString(R.string.x3_orgin_factory_plan_tip);
        Drawable drawable = context.getResources().getDrawable(R.mipmap.x3_main_question);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        //需要处理的文本，"tidai" 是将要被图片替代的位置， + " "   是为了 不让图片紧挨文字
        SpannableString spannable_string = new SpannableString(des + "tidai");
        X3CenterImageSpan imageSpan = new X3CenterImageSpan(drawable);
        spannable_string.setSpan(imageSpan, des.length(), des.length() + "tidai".length(), ImageSpan.ALIGN_BASELINE);
        spannable_string.setSpan(new Clickable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                X3ToastUtils.showMessage(X3OriginalFactoryPlanActivity.this.getString(R.string.x3_maintain_plan_tip));
            }
        }),des.length(), des.length() + "tidai".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_top_tip.setText(spannable_string);
        tv_top_tip.setMovementMethod(LinkMovementMethod.getInstance());

    }

    private void initIntentParams() {
        carId = getIntent().getLongExtra("carId", 0L);
        title = getIntent().getStringExtra("title");
        mainTainPlanBeanList = getIntent().getParcelableArrayListExtra("beanList");
    }

    private void getMainTainPlanListData(long carId) {
        if (mainTainPlanBeanList == null || mainTainPlanBeanList.size() == 0) {
            if (mPresenter != null) {
                mPresenter.getMainTainPlanList(carId);
            }
        } else {
            setMainTainData2UI(mainTainPlanBeanList);
        }
    }

    private void configRlv() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rlv_plan.setLayoutManager(manager);
        mAdapter = new X3OrginFactoryPlanAdapter(this);
        rlv_plan.setAdapter(mAdapter);
    }

    @Override
    protected X3OrginFactoryPresenter createPresenter() {
        return new X3OrginFactoryPresenter();
    }

    @OnClick({R2.id.iv_back, R2.id.rv_cancel, R2.id.rv_affirm})
    public void onViewClick(View view) {
        if (view.getId() == R.id.iv_back || view.getId() == R.id.rv_cancel) {
            finish();
        } else if (view.getId() == R.id.rv_affirm) {
            if (mPresenter != null && mAdapter != null) {
                UpdateMainTainPlan updateMainTainPlan = new UpdateMainTainPlan();
                updateMainTainPlan.carId = carId;
                updateMainTainPlan.maintenanceServiceList = mAdapter.getmList();
                mPresenter.updateMainTainPlan(updateMainTainPlan);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (X3StringUtils.isEmpty(title)) {
            MobclickAgent.onPageEnd(title);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (X3StringUtils.isEmpty(title)) {
            MobclickAgent.onPageStart(title);
        }
    }

    @Override
    public void onMainTainPlanSuccess(List<MainTainPlanBean> list) {
        setMainTainData2UI(list);
    }

    private void setMainTainData2UI(List<MainTainPlanBean> list) {
        if (mAdapter != null) {
            rlv_plan.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    rlv_plan.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    rlv_plan.scrollToPosition(0);
                }
            });
            mAdapter.setDataList(list);
        }
    }

    @Override
    public void updateMainTainPlanSuccess() {
        Handler mHandler = new Handler();
        X3ToastUtils.showMessage(X3OriginalFactoryPlanActivity.this.getString(R.string.x3_orgin_factory_plan_create_success));
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                OptionMainTainPlan plan = new OptionMainTainPlan();
                EventBus.getDefault().post(plan);
                finish();
            }
        },1200);
    }
    @Override
    public void updateMainTainPlanFail(String error) {
        X3ToastUtils.showMessage(error);
    }

    /**
     * 内部类，用于截获点击富文本后的事件
     */
    class Clickable extends ClickableSpan implements View.OnClickListener {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener mListener) {
            this.mListener = mListener;
        }

        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }
}